package serialization;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

public class SerializeToFile {

	public static void serializeStudents(ArrayList<Student> students, String file)
	{
		FileOutputStream fileOut;
		try
		 {
		    fileOut = new FileOutputStream(file);
		    ObjectOutputStream out = new ObjectOutputStream(fileOut);
		    out.writeObject(students);
		    out.close();
		    fileOut.close();
		 }catch(Exception e)
		 {
		     e.printStackTrace();
		     return;
		 }  
		return;
	}
	
	public static ArrayList<Student> deserializeStudents(String file)
	{
		ArrayList<Student> students = null;
	      try
	      {
	         FileInputStream fileIn = new FileInputStream(file);
	         ObjectInputStream in = new ObjectInputStream(fileIn);
	         students = (ArrayList<Student>) in.readObject();
	         in.close();
	         fileIn.close();
	     }catch(Exception e)
	     {
	         e.printStackTrace();   
	         return null;
	     }
	     return students;
	}
	
	public static void main(String args[])
	{
		ArrayList<Student> students = new ArrayList<Student>();
		Student s1 = new Student(1254783,"Amy");
		Student s2 = new Student(1525486,"Ben");
		students.add(s1);
		students.add(s2);
		
		String file="student.ser";
	    serializeStudents(students, file);
	    ArrayList<Student> receivedStudents = deserializeStudents(file);
	    
        for(int i=0; i<receivedStudents.size(); i++)
        {
       	 System.out.println(receivedStudents.get(i).toString());
        }
	}
	
}
